/**
 * 
 */
define(function(require, exports, module){
	"use strict";
	require("resource/js/mobile/css/listview.css");
	require("resource/js/mobile/css/listpanel.css");
	require("resource/js/mobile/jquery.listview.js");
	require("resource/js/mobile/jquery.listpanel.js");
	var AJAX = require("resource/js/component/ajax.js");
	
	function isUndefined(i) {
		return "undefined" == typeof i;
	}
	function isString(i){
		return typeof i == "string";
	}
	var dataUrl = {
			'USER':'/oa/attGroup/queryUserTree.htm'
				}
	
	var books = function(ele,opt){
		this.$element = $(ele);
		this.options = $.extend({},this.defaults,opt);
		var num = Math.ceil(Math.random()*100);
		this.id = "vitoBooks_"+num;
		this.template = '<div id="'+this.id+'"></div>';
		this.init();
	}
	books.defaults = {
			userType : "user",//user,dept,role
			checkType : "checkbox",//checkbox,radio
			closed : false,//初始化后是否立即打开
			url : null,
			data: null,
			onSave : null,
	};

	books.prototype = {
			constructor: books,	
			init : function(){
				var opt = this.options;
				$('body').append(this.template);
				if(opt.userType){
					this.options.url = dataUrl[opt.userType.toUpperCase()]
				}
				
				this.loadPanel();
				!opt.closed && this.open();
			},
			loadPanel : function(){
				var books = this;
				var opt = books.options;
				var checkType= opt.checkType;
				var userType = opt.userType.toUpperCase();
				
				$('#'+books.id).listpanel({
					url: BASEPATH+opt.url,
					dataFilter: function(data) {
						data = data.data;
						for (var i in data) {
							if (data[i].type != userType) {
								data[i].noCheck = true;
								data[i].icon = "icon-group";
							}
						}
						return data;
					},
					data : opt.data,
					view: {
						idKey: "id",
						nameKey: "name",
						pidKey: "pid"
					},
					check: {
						type: checkType,
						checkbox: {
							type: {
								"Y": "p",
								"N": "s"
							}
						},
						radio:{
							type:"all"
						}
					},
					onSave: function(nodes) {
						var a=[];
						$.each(nodes,function(i,val){
						   if(val.type==userType){
							   a.push(val);
						   }
						});	
						books.options.onSave.apply(this,[a]);
					}
				});
				
			},
			open : function(){
				$('#'+this.id).listpanel('show');
			},
	};

	$.fn.vitoBooks = function(conf){
		var r,a=Array.prototype.slice.call(arguments,1);
		return this.each(function(){
			var method,b = $(this).data('vitobooks');
			if(!b){
				$(this).data('vitobooks',b = new books(this,conf));
			}
			isString(conf) && $.isFunction(method = b[conf]) && (r=method.apply(b,a))
		}),isUndefined(r)?this:r
	};
});